ImageGear Java PDF
Split a PDF Document

To split a PDF document:

  1. Use the createDocument method of the PDF class to create a new instance of the Document class.
  2. Use the openDocument method of the Document class to load the PDF document.
  3. Use the createDocument method of the PDF class to create a new instance of the Document class for each of the split PDF documents you want to produce.
  4. Use the insertPages methods of the Document class to insert the specified number of pages of the source PDF document into the resulting split PDF document.
  5. Use the saveDocument method of the Document class to save each split PDF document to a file.
  6. Use the close method of the Document class to close the documents if you do not need them anymore.

The following is an illustration of how to split a PDF document:

 
Copy Code
import com.accusoft.imagegearpdf.*;
 
class PdfDemo
{
        private PDF pdf;
        private Document document;
        private String inputPath;
        
        // Split a PDF document (numberOfPages indicates how many pages the document should be split by).
        public void splitDocument(long numberOfPages)
        {
                long pageCount = this.document.getPageCount();
                
                // The counter of split documents (zero-based indexing).
                int splitDocumentIndex = 0;
                long pagesRemain = pageCount;
                while (pagesRemain > 0)
                {
                        Document splitDocument = this.pdf.createDocument();
                        try
                        {
                                long startPageNumber = splitDocumentIndex * numberOfPages;
                                long pagesToInsert = pagesRemain > numberOfPages ? numberOfPages : pagesRemain;
                                splitDocument.insertPages(0, this.document, startPageNumber, pagesToInsert);
                                ++splitDocumentIndex;
 
                                String outputPath = inputPath + "_" + splitDocumentIndex + ".pdf";
                                this.savePdf(splitDocument, outputPath);
                                pagesRemain -= numberOfPages;
                        }
                        finally
                        {
                                splitDocument.close();
                                splitDocument = null;
                        }
                }
        }
}

See Also

 

 


©2016. Accusoft Corporation. All Rights Reserved.

Send Feedback